package com.h3bpm.kumhosunny.sample.controller;

import OThinker.Common.Organization.Models.Unit;
import OThinker.Common.Organization.Models.User;
import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Entity.DataModel.BizObject;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.h3bpm.base.util.AppUtility;
import com.h3bpm.kumhosunny.common.utils.SqlUtil;
import com.h3bpm.kumhosunny.sample.controller.utils.NemberUtil;
import com.h3bpm.kumhosunny.sample.controller.utils.SampleNoUtil;
import data.DataRow;
import data.DataTable;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: wjq
 * @Date: 2019/9/23 18:37
 * @Description:样品流程
 */
@Controller
@RequestMapping({"/Portal/Sample"})
public class SampleController extends ControllerBase {

    private static Logger log = LoggerFactory.getLogger(SampleController.class);


    @Value("${web_service_sample_url}")
    private String webServiceSampleUrl;



    @RequestMapping(value = "/requestSampleData")
    @ResponseBody
    public JSONObject requestSampleData(String itemNo ,String appNo){

        JSONObject jsonResult = new JSONObject();
        jsonResult.put("status",200);
        JSONObject data = new JSONObject();
        try {
          SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String getInstanceIdSql =   "select b.ObjectID as instanceId, a.* from i_sampleApplication a inner join ot_instancecontext b on a.ObjectID=b.BizObjectId where a.itemNo='"+itemNo+"' and a.applicationNo='"+appNo+"'";
            DataTable dataTable  = null;
            dataTable = SqlUtil.doQuery(getInstanceIdSql);
            if(dataTable!=null && dataTable.getEntityRows()!=null && dataTable.getEntityRows().size()>0) {
              //  String instentPreId = dataTable.getEntityRows().get(0).getString("instanceId");
                //InstanceData instanceDataPre = new InstanceData(AppUtility.getEngine(), instentPreId, User.AdministratorID);
                DataRow preData = dataTable.getEntityRows().get(0);
                if(preData.getObject("projectPurpose")!=null) {
                    data.put("projectPurpose",preData.getString("projectPurpose"));
                }
                if(preData.getObject("productsSurface")!=null) {
                    data.put("productsSurface",preData.getString("productsSurface"));
                }

                if(preData.getObject("thickness")!=null) {

                    data.put("thickness",preData.getString("thickness"));

                }
                if(preData.getObject("customerYtTd")!=null) {
                    data.put("customerYtTd",preData.getString("customerYtTd"));
                }
                if(preData.getObject("ResearchAssociate")!=null) {
                    data.put("ResearchAssociate",preData.getString("ResearchAssociate"));
                }

                if(preData.getObject("backOffice")!=null) {
                    data.put("backOffice",preData.getString("backOffice"));
                }

                if(preData.getObject("sopTime")!=null) {
                    data.put("sopTime",simpleDateFormat.format(preData.getDate("sopTime")));
                }

                if(preData.getObject("eopTime")!=null) {
                    data.put("eopTime",simpleDateFormat.format(preData.getDate("eopTime")));
                }


                if(preData.getObject("dateBeginProducing")!=null) {
                    data.put("dateBeginProducing",simpleDateFormat.format(preData.getDate("dateBeginProducing")));
                }

                if(preData.getObject("KsHostssaleman")!=null) {
                    data.put("KsHostssaleman", preData.getString("KsHostssaleman") );
                }




                // 处理子表
             /*   BizObject[] detailTable = (BizObject[])instanceDataPre.getBizObject().getValueTable().get("sampleInformation");
                List<HashMap<String,Object>> detailValueList = new ArrayList<>();
                if ( null != detailTable) {
                    for (int i = 0;i< detailTable.length;i++) {
                        BizObject detail  = detailTable[i];
                         detailTable[i].setOwnerParentId(instanceData.getBizObject().getObjectID());
                        detailTable[i].setObjectID(UUID.randomUUID().toString());
                        HashMap<String,Object> detailValue = new HashMap<>(2);
                        HashMap<String, Object> detailValueTable = detail.getValueTable();
                        detailValue.put("spline",detailValueTable.get("spline"));
                        detailValue.put("splineStandard",detailValueTable.get("splineStandard"));
                        detailValue.put("categoryColor",detailValueTable.get("categoryColor"));
                        detailValue.put("swatches",detailValueTable.get("swatches"));
                        detailValueList.add(detailValue);


                    }
                }*/
               //  instanceData.getBizObject().getValueTable().put("sampleInformation",detailTable);
               // instanceData.getBizObject().setItem("sampleInformation",detailTable);
              //  instanceData.Submit();

                jsonResult.put("data",data);
               // AppUtility.getEngine().getBizObjectManager().RemoveAttachments("sampleApplication", instanceData.getBizObject().getObjectID(), "performanceCriteria");
                //AppUtility.getEngine().getBizObjectManager().CopyAttachments("sampleApplication", instanceDataPre.getBizObject().getObjectID(), "performanceCriteria", "sampleApplication", instanceData.getBizObject().getObjectID(), "performanceCriteria", true);

            }

        } catch (Exception e) {
            jsonResult.put("status",500);
            jsonResult.put("data","系统异常");
                e.printStackTrace();
            }

           return jsonResult;
    }


    /**
     * 赋值附件
     *
     * @param sourceBizObjectId      源数据实体ID
     * @param sourceBizObjectSchemaCode  源数据模型编码
     * @param sourceDataField         源附件类型数据项编码
     * @param destBizObjectId          目标数据实体ID
     * @param destBizObjectSchemaCode   目标附件类型数据项编码
     * @param destDataField
     * @authormi
     * @date2020/01/07
     */
    @RequestMapping("/setAttachment")
    @ResponseBody
    public void setAttachment(String sourceBizObjectId, String sourceBizObjectSchemaCode, String sourceDataField, String destBizObjectId, String destBizObjectSchemaCode, String destDataField) throws Exception {
        AppUtility.getEngine().getBizObjectManager().CopyAttachments(sourceBizObjectSchemaCode, sourceBizObjectId, sourceDataField, destBizObjectSchemaCode, destBizObjectId, destDataField, true);
    }


    @RequestMapping("/addTableData")
    @ResponseBody
    public void insertTwoTable(){




    }



    /**
     *
     //页面加载执行的时间自动生成一个 ，保存的时候必须校验防止并发生成相同的编号
     *
     * @param:
     * @return:
     * @auther: Administrator
     * @date: 2019/11/27 11:22
     */
    @RequestMapping(value = "/newSampleNo")
    @ResponseBody
    public JSONObject newSampleNo(String address){
        log.info("获取最新的样品申请单号部门==========address"+address);
        if(address==null||address.isEmpty()){
            return null;
        }
        String newAddress =SampleNoUtil.getOuName(address);
        JSONObject result= new JSONObject();
        Map<String, String> customerMap =  Collections.synchronizedMap(new HashMap<String, String>(16));
        customerMap= SampleNoUtil.sampleNember(newAddress);
        result.put("data",customerMap);
        result.put("status","200");
        return result;

    }
    /**
     *
     //映射的时候使用，对应的轮数加1
     *
     * @param:
     * @return:
     * @auther: Administrator
     * @date: 2019/11/28 19:22
     */
    @RequestMapping(value = "/mappingSampleNo")
    @ResponseBody
    public JSONObject mappingSampleNo(String itemNo,String bizoBjectId) {
        log.info("样品申请项目号映射接口生成新的申请单编号==========itemNo"+itemNo);
        if(itemNo==null||itemNo.isEmpty()){
            return null;
        }
        JSONObject result = new JSONObject();
        try {
            String sql = "select applicationNo,objectId from i_sampleapplication where itemNo='"+itemNo+"'  and  applicationNo like'"+itemNo+"%'  and applicationNo is not null  ORDER BY applicationNo desc LIMIT 1";


            DataTable dataTable = SqlUtil.doQuery(sql);
            List<DataRow> entityRows = dataTable.getEntityRows();
            String applicationNo = null;
            String objectid=null;
            if (entityRows.isEmpty()) {
            } else {
                DataRow dataRow = entityRows.get(0);
                applicationNo = dataRow.getString("applicationNo");
                objectid = dataRow.getString("objectId");
            }
            //判断项目是否存
            if (applicationNo == null || applicationNo.isEmpty()) {
                return null;
            } else {
                String oldNemner=applicationNo.substring(applicationNo.length()-2,applicationNo.length());
                Integer nember=Integer.valueOf(oldNemner);
                String no ="";
                if(bizoBjectId!=null && bizoBjectId.equals(objectid)){
                    no = NemberUtil.nemberStr2(nember);
                }else {
                      no = NemberUtil.nemberStr2(nember + 1);
                }
                // 根据规则生成新的申请单编号
                applicationNo = itemNo+"-"+no;
                result.put("data", applicationNo);
                result.put("status", "200");
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     *
     //校验的使用 防止并发出现数据相同的数据
     *
     * @param:
     * @return:
     * @auther: Administrator
     * @date: 2019/11/29 11:22
     */
    @RequestMapping(value = "/CheckSampleNo")
    @ResponseBody
        public JSONObject checkSampleNo(String applicationNo,String itemNo,String ObjectId) throws Exception {

        String newItemNumberStrtest=itemNo.substring(itemNo.length()-4,itemNo.length());
        String newItemNumberStrAftertest=itemNo.substring(0,itemNo.length()-4);
        Integer newItemNumbertest=Integer.valueOf(newItemNumberStrtest);
        String itemStrtest = String.format("%04d", newItemNumbertest+1);
       String applicationNotest = newItemNumberStrAftertest+itemStrtest + "-" + "01";
         System.out.println(applicationNotest);
        log.info("样品申请项目号验证接口=================applicationNo"+applicationNo);
        Integer test=Integer.valueOf("0001");
        System.out.println(test);
        JSONObject result = new JSONObject();


    if(applicationNo==null||applicationNo.isEmpty()) {
       String applicationSql = "select  applicationNo from i_sampleapplication    where itemNo = '"+itemNo+"'  and  applicationNo like'"+itemNo+"%'   and applicationNo is not null    ORDER BY createdTime desc    LIMIT 1";
       DataTable dTable = SqlUtil.doQuery(applicationSql);
        if(dTable != null &&  dTable.getEntityRows().size()>0){
            DataRow dataRow = dTable.getEntityRows().get(0);
            String no = dataRow.getString(0);
            String oldNo=no.substring(applicationNo.length()-2,applicationNo.length());
            Integer number=Integer.valueOf(oldNo);
            String  newNo = NemberUtil.nemberStr2(number + 1);
            applicationNo = itemNo + "-" + newNo;
        }else{
            applicationNo = itemNo + "-01";
        }
        result.put("data", applicationNo);
        result.put("status", "200");
        return result;
    }

   String newApplicationNo = SampleNoUtil.checkApplicationNoAndItemNo(itemNo,ObjectId);


    if(newApplicationNo==null||newApplicationNo.isEmpty()) {
        result.put("data", itemNo+"-01");
        result.put("status", "200");
        return result;
    }
        String oldNemner=applicationNo.substring(applicationNo.length()-2,applicationNo.length());
        Integer nember=Integer.valueOf(oldNemner);
        String newNemner=newApplicationNo.substring(newApplicationNo.length()-2,newApplicationNo.length());
        Integer newNo=Integer.valueOf(newNemner);
        String no="";
        if(newNo>=nember) {
            if("01".equals(oldNemner)) {
                String newItemNumberStr=itemNo.substring(itemNo.length()-4,itemNo.length());
                String newItemNumberStrAfter=itemNo.substring(0,itemNo.length()-4);
                Integer newItemNumber=Integer.valueOf(newItemNumberStr);
                String itemStr = String.format("%04d", newItemNumber+1);
                String newItemNo=newItemNumberStrAfter + itemStr;
                String sql = "select itemNo from i_sampleapplication where itemNo='"+ newItemNo +"'    and  applicationNo like'"+newItemNo+"%' ORDER BY createdTime desc LIMIT 1";
                DataTable dataTable = SqlUtil.doQuery(sql);
                List<DataRow> entityRows = dataTable.getEntityRows();
                if (entityRows.isEmpty()) {
                    newApplicationNo = newItemNo + "-01";
                } else {
                    String  prefix =  newItemNo.substring(0,2);
                      sql = "select itemNo from i_sampleapplication  where itemNo like '"+prefix+"%' and applicationNo like '%01'  ORDER BY createdTime desc LIMIT 1";
                      dataTable = SqlUtil.doQuery(sql);
                     entityRows = dataTable.getEntityRows();
                    DataRow dataRow = entityRows.get(0);
                    newItemNo = dataRow.getString(0);
                      newItemNumberStr=newItemNo.substring(newItemNo.length()-4,newItemNo.length());
                      newItemNumberStrAfter=newItemNo.substring(0,newItemNo.length()-4);
                      newItemNumber=Integer.valueOf(newItemNumberStr);
                      itemStr = String.format("%04d", newItemNumber+1);
                    newApplicationNo = newItemNumberStrAfter+itemStr+ "-01";
                }

            }else {
                applicationNo = newApplicationNo;
            }
        }
        applicationNo=newApplicationNo;
        // 根据规则生成新的申请单编号
        result.put("data", applicationNo);
        result.put("status", "200");
        return result;
    }









    @RequestMapping(value = "/insertU8Sample")
    @ResponseBody
   public JSONObject  insertU8Sample(String instanceId){

        JSONObject result = new JSONObject();
        result.put("status","200");
        result.put("successData", "T");
        try {
            InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
            SimpleDateFormat formatData= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
           Map<String,Object>  data =  instanceData.getBizObject().getValueTable();

            JSONObject dataJson = new JSONObject();
           for(String key : data.keySet()){
                if(!"sampleInformation".equals(key)) {
                    if(data.get(key) instanceof Date || data.get(key) instanceof Timestamp) {
                        if(data.get(key)!=null) {
                            String dateStr = formatData.format(data.get(key));
                            dataJson.put(key, dateStr);
                        }else{
                            dataJson.put(key, "");
                        }
                    }
                    if("CreatedBy".equals(key) || "ModifiedBy".equals(key) ||  "applicant".equals(key) ||  "fillPerson".equals(key) ||  "customerProjectManager".equals(key) ||  "backOffice".equals(key)  ||  "businessDepartments".equals(key) ||  "ResearchAssociate".equals(key )) {
                       if(!"businessDepartments".equals(key) && data.get(key)!=null) {
                           String person = data.get(key).toString();
                           if(!"".equals(person)) {
                               User user = (User) getEngine().getOrganization().GetUnit(person);
                               dataJson.put(key, user.getName());
                           }else{
                               dataJson.put(key, "");
                           }
                       } else{
                           dataJson.put(key, "");
                       }

                        if( "businessDepartments".equals( key) && data.get(key)!=null) {
                            String businessDepartments = data.get("businessDepartments").toString();
                            Unit unit =   getEngine().getOrganization().GetUnit(businessDepartments);
                            dataJson.put(key, unit.getName());
                        }else if( "businessDepartments".equals(key) && data.get(key)==null){
                            dataJson.put(key, "");
                        }
                    }else if(!(data.get(key) instanceof Date || data.get(key) instanceof Timestamp)){
                            if(data.get(key)!=null) {
                                dataJson.put(key, data.get(key).toString());
                            }else{
                                dataJson.put(key, "");
                            }
                        }
                }

           }
            dataJson.put("instanceId",instanceId);
            JSONArray jsonArray = new JSONArray();
            if(data.get("sampleInformation")!=null) {
                BizObject[] sampleInformation = (BizObject[]) data.get("sampleInformation");
                for (BizObject childObj : sampleInformation) {
                    JSONObject dataChildJson = new JSONObject();
                    Map<String, Object> zbValueTable = childObj.getValueTable();
                    dataChildJson.put("spline", zbValueTable.get("spline").toString());
                    dataChildJson.put("splineStandard", zbValueTable.get("splineStandard").toString());
                    dataChildJson.put("categoryColor", zbValueTable.get("categoryColor").toString());
                    dataChildJson.put("swatches", zbValueTable.get("swatches").toString());
                    jsonArray.add(dataChildJson);
                }
                dataJson.put("sampleInformation", jsonArray);
            }else{
                dataJson.put("sampleInformation","");
            }
           String u8Result = callU8InsertData(dataJson.toJSONString());
            JSONObject jsonResult = JSONObject.parseObject(u8Result);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String createTime = simpleDateFormat.format(new Date());
            if(jsonResult.containsKey("RESULTList")) {
                JSONArray array = jsonResult.getJSONArray("RESULTList");
                if (array.size() > 0) {
                    JSONObject jsonObj = array.getJSONObject(0);
                    if (jsonObj.containsKey("Result")) {
                        String strResult = jsonObj.getString("Result");
                        if("T".equals(strResult)){
                            writeSampleProcessSataus(  null,   null,   "材料开发",   instanceId,createTime);
                            result.put("sampleFromStu", "材料开发");
                            result.put("sampleFromstarTime",createTime);
                        }
                        result.put("success", u8Result);
                        result.put("successData", strResult);
                    }else{
                        result.put("success", u8Result);
                        result.put("sampleFromStu", "");
                        result.put("sampleFromstarTime","");
                    }
                } else {
                    result.put("success", u8Result);
                    result.put("sampleFromStu", "");
                    result.put("sampleFromstarTime","");
                }
            }

           result.put("success",u8Result);

        } catch (Exception e) {
            result.put("status","500");
            result.put("sampleFromStu", "");
            result.put("sampleFromstarTime","");
            e.printStackTrace();
        }
        return result;
   }


    @RequestMapping(value = "/insertU8SampleFeedback")
    @ResponseBody
    public JSONObject insertU8SampleFeedback(String instanceId){

        JSONObject result = new JSONObject();
        result.put("status","200");
        result.put("successData", "T");
        try {
            InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
            SimpleDateFormat formatData= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Map<String,Object>  data =  instanceData.getBizObject().getValueTable();
            JSONObject dataJson = new JSONObject();
            for(String key : data.keySet()){
                    if(data.get(key) instanceof Date || data.get(key) instanceof Timestamp) {
                        if(data.get(key)!=null) {
                            String dateStr = formatData.format(data.get(key));
                            dataJson.put(key, dateStr);
                        }else{
                            dataJson.put(key, "");
                        }
                    }
                    if(  "CreatedBy".equals(key) || "ModifiedBy".equals(key) || "applicant".equals(key) || "feedbackPeople".equals(key) || "fillPerson".equals(key) ) {
                        if(  data.get(key)!=null) {
                            String person = data.get(key).toString();
                            if(!"".equals(person)) {
                                User user = (User) getEngine().getOrganization().GetUnit(person);
                                dataJson.put(key, user.getName());
                            }else{
                                dataJson.put(key, "");
                            }
                        } else{
                            dataJson.put(key, "");
                        }
                    }else if(!(data.get(key) instanceof Date || data.get(key) instanceof Timestamp)){
                        if(data.get(key)!=null) {
                            dataJson.put(key, data.get(key).toString());
                        }else{
                            dataJson.put(key, "");
                        }
                    }
            }
            dataJson.put("instanceId",instanceId);
            String u8Result = callTestU8Feedback(dataJson.toJSONString());
            JSONObject jsonResult = JSONObject.parseObject(u8Result);
            if(jsonResult.containsKey("RESULTList")) {
                JSONArray array = jsonResult.getJSONArray("RESULTList");
                if (array.size() > 0) {
                    JSONObject jsonObj = array.getJSONObject(0);
                    if (jsonObj.containsKey("Result")) {
                        String strResult = jsonObj.getString("Result");
                        result.put("success", u8Result);
                        result.put("successData", strResult);
                    }else{
                        result.put("success", u8Result);
                    }
                } else {
                    result.put("success", u8Result);
                }
            }

        } catch (Exception e) {
            result.put("status","500");
            e.printStackTrace();
        }
        return result;
    }




    public String callU8InsertData(String sampleData) throws  IOException {
        ServiceClient sc = new ServiceClient();
        Options opts = new Options();
        String url = webServiceSampleUrl;
        EndpointReference end = new EndpointReference(url);
        opts.setTo(end);
        opts.setAction("http://tempuri.org/YFSQImport");
        sc.setOptions(opts);
        OMFactory fac = OMAbstractFactory.getOMFactory();
        OMNamespace omNs = fac.createOMNamespace("http://tempuri.org/", "");
        OMElement method = fac.createOMElement("YFSQImport",omNs);
        OMElement value = fac.createOMElement("strJSON",omNs);
        value.setText(sampleData);
        method.addChild(value);
        OMElement res = sc.sendReceive(method);
        return res.getFirstElement().getText();
    }



    public String  callTestU8Feedback(String sampleData) throws   IOException {
        ServiceClient sc = new ServiceClient();
        Options opts = new Options();
        String url = webServiceSampleUrl;
        EndpointReference end = new EndpointReference(url);
        opts.setTo(end);
        opts.setAction("http://tempuri.org/FKXXImport");
        sc.setOptions(opts);
        OMFactory fac = OMAbstractFactory.getOMFactory();
        OMNamespace omNs = fac.createOMNamespace("http://tempuri.org/", "");
        OMElement method = fac.createOMElement("FKXXImport",omNs);
        OMElement value = fac.createOMElement("strJSON",omNs);
        value.setText(sampleData);
        method.addChild(value);
        OMElement res = sc.sendReceive(method);
        return res.getFirstElement().getText();
    }




    public int writeSampleProcessSataus(String itemNumber, String applicationNo, String statesName, String instentsId,  String createTime) {

        try {
            String createBy = "";
            if (instentsId != null && !"".equals(instentsId)) {
                InstanceData instanceData = null;
                instanceData = new InstanceData(AppUtility.getEngine(), instentsId, User.AdministratorID);

                instanceData.getBizObject().setItem("procesState", statesName);
                instanceData.getBizObject().setItem("processStarTime", createTime);
                instanceData.Submit();
                itemNumber = "";
                applicationNo = "";
                if (instanceData.getBizObject().getItem("itemNo") != null) {
                    itemNumber = instanceData.getBizObject().getItem("itemNo").toString();
                }
                if (instanceData.getBizObject().getItem("applicationNo") != null) {
                    applicationNo = instanceData.getBizObject().getItem("applicationNo").toString();
                }
                createBy = instanceData.getInstanceContext().getOriginator();
            } else {
                String getInstanceIdSql = "select b.ObjectID from i_sampleApplication a inner join ot_instancecontext b on a.ObjectID=b.BizObjectId where a.itemNo='" + itemNumber + "' and a.applicationNo='" + applicationNo + "'";
                DataTable dataTable = SqlUtil.doQuery(getInstanceIdSql);
                if (dataTable != null && dataTable.getEntityRows() != null && dataTable.getEntityRows().size() > 0) {
                    instentsId = dataTable.getEntityRows().get(0).getString("ObjectID");
                    InstanceData instanceData = new InstanceData(AppUtility.getEngine(), instentsId, User.AdministratorID);
                    instanceData.getBizObject().setItem("procesState", statesName);
                    instanceData.getBizObject().setItem("processStarTime", createTime);
                    instanceData.Submit();
                    itemNumber = "";
                    applicationNo = "";
                    if (instanceData.getBizObject().getItem("itemNo") != null) {
                        itemNumber = instanceData.getBizObject().getItem("itemNo").toString();
                    }
                    if (instanceData.getBizObject().getItem("applicationNo") != null) {
                        applicationNo = instanceData.getBizObject().getItem("applicationNo").toString();
                    }
                    createBy = instanceData.getInstanceContext().getOriginator();
                }
            }
            String getLastTimeSql = "select ObjectId from k_samplestate where itemNumber = '" + itemNumber + "' and applicationNo = '" + applicationNo + "' order by  CreatedTime desc";
            DataTable dataTable = SqlUtil.doQuery(getLastTimeSql);
            String lastObjectId = "";
            if (dataTable != null && dataTable.getEntityRows() != null && dataTable.getEntityRows().size() > 0) {
                lastObjectId = dataTable.getEntityRows().get(0).getString("ObjectId");
                String updateU8State = "update k_samplestate set ModifiedTime = '" + createTime + "' where  ObjectId= '" + lastObjectId + "'";
                SqlUtil.doNoQuery(updateU8State);
            }
            String insertU8State = "insert into k_samplestate ( itemNumber,statesName,instentsId,ObjectId,CreatedTime,CreatedBy,ModifiedTime,ModifiedBy,applicationNo)";
            String objectId = UUID.randomUUID().toString();
            insertU8State = insertU8State + " values ('" + itemNumber + "','" + statesName + "','" + instentsId + "','" + objectId + "','" + createTime + "','" + createBy + "','" + createTime + "','" + createBy + "','" + applicationNo + "')";
            SqlUtil.doNoQuery(insertU8State);
        } catch (Exception e) {
            e.printStackTrace();
            return 500;
        }
        return 200;
    }

    @Override
    public String getFunctionCode() {
        return null;
    }
}
